

package cn.shengchao.examstar.comment.ohs.local.appservice;

import cn.shengchao.examstar.comment.acl.adapters.clients.AiClient;
import cn.shengchao.examstar.comment.acl.adapters.clients.UserClient;
import cn.shengchao.examstar.comment.acl.ports.repositories.IProductCommentRepository;
import cn.shengchao.examstar.comment.domain.valobj.Student;
import cn.shengchao.examstar.comment.ohs.local.message.CommentDto;
import cn.shengchao.examstar.shared.application.ai.dto.CommentsFilterAndRateResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;

@Slf4j
@Service
public class ProductCommentAppService {
    @Autowired
    private IProductCommentRepository productCommentRepository;

    @Autowired
    private UserClient userClient;
    @Autowired
    private AiClient aiClient;
    @Autowired
    private AsyncTaskExecutor asyncTaskExecutor;

    public void comment(CommentDto commentDto, Long userId) {
        CompletableFuture.runAsync(() -> {
            Student student = userClient.getStudentInfo(userId);
            log.info("获取用户信息：{},{}", userId, student.getName());
            CommentsFilterAndRateResult commentsFilterAndRateResult = aiClient.filterAndRate(commentDto.getContent());
            log.info("评论过滤结果：{}", commentsFilterAndRateResult);
            productCommentRepository.save(commentDto.toProductComment(student, commentsFilterAndRateResult));
        }, asyncTaskExecutor).exceptionally(throwable -> {
            log.error("评论失败:{},{}", userId, throwable.getMessage());
            return null;
        });

    }
}
